#!/usr/bin/env python
import pika
import sys

"""
主题模式(topic, 相当于模糊匹配routing_key, key相同的消费者会同时受到消息)

1. 申请交换机
    - 设置主题模式topic

2. 申请队列
3. 绑定队列
    - 根据routing_key: 
        - *（星号）可以完全代替一个单词。
        - # (hash) 可以替换零个或多个单词。
"""

credentials = pika.PlainCredentials(username='chf', password='123456')  # mq用户名和密码
connection = pika.BlockingConnection(pika.ConnectionParameters(host='117.72.79.182', port=5672, credentials=credentials))
channel = connection.channel()

channel.exchange_declare(exchange='topic_logs', exchange_type='topic')

result = channel.queue_declare('', exclusive=True)
queue_name = result.method.queue

binding_keys = sys.argv[1:]
if not binding_keys:
    sys.stderr.write("Usage: %s [binding_key]...\n" % sys.argv[0])
    sys.exit(1)

for binding_key in binding_keys:
    channel.queue_bind(
        exchange='topic_logs', queue=queue_name, routing_key=binding_key)

print(' [*] Waiting for logs. To exit press CTRL+C')


def callback(ch, method, properties, body):
    print(f" [x] {method.routing_key}:{body}")


channel.basic_consume(
    queue=queue_name, on_message_callback=callback, auto_ack=True)

channel.start_consuming()


# python receive_logs_topic.py "#"
# python receive_logs_topic.py "kern.*"
# python receive_logs_topic.py "*.critical"
# python receive_logs_topic.py "kern.*" "*.critical"

# python emit_log_topic.py "kern.critical" "A critical kernel error"